介紹
橋接模式將介面與實作分離,提升兩者變化的彈性。
以下展示皮老闆成功偷取蟹堡秘方後,海之霸開始賣蟹堡
C++範例
#include <iostream>
// 抽象漢堡祖傳秘方
class HamburgerFormula
{
public:
virtual void Make(int elem1, int elem2, int elem3) = 0;
virtual ~HamburgerFormula() {}
};
// 蟹堡祖傳秘方
class KrabsFormula : public HamburgerFormula
{
public:
void Make(int elem1, int elem2, int elem3) override
{
std::cout << "Krabs's hamburger: Add " << elem1 << "% lettuce, " << elem2 << "% onions, " << elem3 << "% cheese" << std::endl;
}
};
// 海之霸祖傳秘方
class PlanktonFormula : public HamburgerFormula
{
public:
void Make(int elem1, int elem2, int elem3) override
{
std::cout << "Plankton's hamburger: Add " << elem1 << "% lettuce, " << elem2 << "% onions, " << elem3 << "% cheese" << std::endl;
}
};
// 抽象漢堡店
class HamburgerRestaurant
{
public:
virtual ~HamburgerRestaurant() {}
virtual void MakeHamburger() = 0;
};
// 海之霸漢堡店
class ChumBucket : public HamburgerRestaurant
{
public:
ChumBucket(int elem1, int elem2, int elem3, HamburgerFormula *hamburgerFormula) :
m_elem1(elem1),
m_elem2(elem2),
m_elem3(elem3),
m_HamburgerFormula(hamburgerFormula)
{
}
void MakeHamburger()
{
m_HamburgerFormula->Make(m_elem1, m_elem2, m_elem3);
}
private:
int m_elem1;
int m_elem2;
int m_elem3;
HamburgerFormula *m_HamburgerFormula;
};
int main(void)
{
// 皮老闆成功偷到蟹堡秘方,海之霸現在也賣蟹堡
ChumBucket krabs(30, 50, 20, new KrabsFormula());
ChumBucket plankton(0, 0, 100, new PlanktonFormula());
krabs.MakeHamburger();
plankton.MakeHamburger();
return 0;
}
Output:
Krabs's hamburger: Add 30% lettuce, 50% onions, 20% cheese
Plankton's hamburger: Add 0% lettuce, 0% onions, 100% cheese